# -*- coding: utf-8 -*-
'''
Created on 2012-06-09

@author: alexandre
'''


# Import CherryPy global namespace
import cherrypy
from mlEval.util import readFile
from cherrypy.lib.static import serve_file
from os import path, listdir
from shutil import rmtree
import time as t
from mlEval.report import unparseLossLDD, TestInfo, Report
import tempfile 
from threading import Timer

siteFolder= path.dirname( path.abspath( __file__ ) )
#print siteFolder

expirationDelay = 60 # seconds
gcDelay = 10 # garbage collector delay in seconds



def readLossFile(fd): 
    lossLDD_txtL = []
    while True:
        data = fd.read(8192)
        if not data: break
        lossLDD_txtL.append(data)
    return ''.join( lossLDD_txtL )

def generateReport(lossLDD):
    testInfo = TestInfo(lossLDD)
    report = Report(testInfo, sgnTest=True, wsrTest=True, showIndividualRisk=True)
    tmpDir = tempfile.mkdtemp(dir=path.join(siteFolder,'tmp'))
    report.texDoc.build( cmd='pdflatex', filePrefix='report', folder=tmpDir)
    pdfPath = path.relpath( path.join( tmpDir, 'report.pdf' ), siteFolder )
    texPath = path.relpath( path.join( tmpDir, 'report.tex' ), siteFolder )
    return pdfPath, texPath

class MlEvalServer(object):
    
    _cp_config = {
         'tools.staticdir.on'    : True,
         'tools.staticdir.dir'   : siteFolder,
         'tools.staticdir.index' : 'index.html',
         'tools.encode.encoding' : "utf-8",
         }
    
    @cherrypy.expose
    def upload(self, **argD):
        
        
        
        fileContent = readFile(siteFolder, "index.html")
        
        if len(argD) == 0:
            return fileContent
        
        myFile = argD['myFile']
        
        
        appendContentL = []
        
        if myFile.file is None:
            appendContent = """<div class="alert alert-error">Please select a file</div>"""
            return fileContent.replace("<!--replace-after-form-->", appendContent ,1)
        
        
        lossLDD_txt = readLossFile( myFile.file )
        
        if len(lossLDD_txt.strip()) == 0:
            appendContent = """<div class="alert alert-error">Please select a file</div>"""
            return fileContent.replace("<!--replace-after-form-->", appendContent ,1)
        
        try:
            lossLDD, warningL = unparseLossLDD(lossLDD_txt)
        except Exception as exc:
            appendContent = """<div class="alert alert-error">Could not parse the loss file.</br> %s </div>"""%(exc.args[0])
            return fileContent.replace("<!--replace-after-form-->", appendContent ,1)
        
        for warning in warningL:
            appendContentL.append( """<div class="alert alert-block">Warning!</br> %s </div>"""%(warning) )
        
        pdfPath, texPath = generateReport( lossLDD )
        
        appendContentL.append( """<div class="alert alert-info"><a href="%s">report.pdf</a> | <a href="%s">report.tex</a></div>"""%(pdfPath, texPath) )
            
        return fileContent.replace("<!--replace-after-form-->",  "\n".join( appendContentL ) ,1)
#        return serve_file(self.pdfPath, "application/x-download", "attachment")

def garabageCollector(siteFolder, expirationDelay,gcDelay):
    tmpDir = path.join(siteFolder, 'tmp')
    for name in listdir(tmpDir):
        folder = path.join( tmpDir, name )
        delay = t.time() - path.getmtime( folder ) 
        if delay > expirationDelay:
            if path.isdir(folder):
                rmtree( folder )
    timer = Timer(gcDelay, garabageCollector, (siteFolder, expirationDelay,gcDelay) )
    timer.start()


if __name__ == "__main__":
    timer = Timer(gcDelay, garabageCollector, (siteFolder, expirationDelay,gcDelay) )
    timer.start()
    cherrypy.quickstart(MlEvalServer())
    